package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author fanYuLe
 * @Date 2023/3/2 12:11
 * @Blog blog.fanYuLe.net/996.mba
 * @Description:
 */
@RestController
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询菜品分类列表
    @GetMapping("/category/findAll")
    public ResultInfo findAll(){
        List<Category> list=null;
        //先查询缓存
        String categoryKey="category_list";
        if(redisTemplate.hasKey(categoryKey)){
            //yse redis有数据
            list = (List<Category>) redisTemplate.opsForValue().get(categoryKey);
            log.info("查询redis缓存");
        }else {
            //no redis没有数据
            //调用service查询mysql
            list=categoryService.findAll();
            log.info("查询mysql缓存");
            //同步到redis中
            redisTemplate.opsForValue().set(categoryKey,list);
        }

        return ResultInfo.success(list);
    }

    //新增分类
    @PostMapping("/category")
    public ResultInfo save(@RequestBody Category category){
        categoryService.save(category);
        //清理redis缓存
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //修改分类
    @PutMapping("/category")
    public ResultInfo update(@RequestBody Category category){
        categoryService.update(category);
        //清理redis缓存
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }
    //删除分类
    @DeleteMapping("/category")
    public ResultInfo deleteById(Long id){

       /* ResultInfo resultInfo=categoryService.deleteById(id);
        return resultInfo;*/

        categoryService.deleteById(id);
        //清理redis缓存
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //根据type查询分类列表
        //select * from category where type = 1;
    @GetMapping("/category/list")
    public ResultInfo list(Integer type){
        return ResultInfo.success(categoryService.list(type));
    }
}

